<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 插槽部分 -->
      <page-Tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" :disabled="!checkPermissions('excel-dao')" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" :disabled="!checkPermissions('excel-dao')" @click="handledDownLoad">excel导出</el-button>
          <el-button :disabled="!checkPermissions('tianjia')" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-Tools>
      <!-- 权限设计模态框 -->
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <!-- 二维码模态框 -->
      <el-dialog width="300px" title="二维码" :visible="showCodeDialog" @close="closeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 卡片部分 -->
      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="图片" sortable="">
            <template #default="{row}">
              <img v-imgerror="defaultImage" class="staff" :src="row.staffPhoto || defaultImage" alt="" @click="openDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermissions('shanchu')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
        <add-employee :show-dialog.sync="showDialog" @add-employee="getreqGetEmployeeList" />
      </el-card>
    </div>
  </div>
</template>

<script>
import checkPermissions from '@/mixins/checkPermissions'
import QrCode from 'qrcode'
import EmployeeEnum from '@/api/constant/employees'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
// import dayjs from 'dayjs'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  mixins: [checkPermissions],
  // 局部过滤器
  // filters: {
  //   formatDate(value) {
  //     return dayjs(value).format('YYYY年MM月DD日')
  //   }
  // },
  data() {
    return {
      showCodeDialog: false,
      // 默认图片
      defaultImage: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.bizhizu.com%2Fpic_source%2Fe4%2F03%2F73%2Fe4037326ad26fabb507bdbece55ffd88.jpg&refer=http%3A%2F%2Fup.bizhizu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673687638&t=72b042d95fc71c04aaf500c86c5e3721',
      // 渲染得出的数据
      list: [],
      // 默认页数
      page: 1,
      // 默认一页十条数据
      pageSize: 10,
      // 总数据
      total: 0,
      loaing: false,
      // 模态框
      showDialog: false,
      // 权限设计的模态框
      showRoleDialog: false,
      // 权限设计需要传的id
      userId: ''

    }
  },
  created() {
    this.getreqGetEmployeeList()
  },
  methods: {
    // 在这里使用mixins混入，
    // 点击弹出二维码模态框
    openDialog(url) {
      if (!url) return this.$message.success('此员工还没有上传图片')
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 关闭二维码模态框
    closeDialog() {
      this.showCodeDialog = false
    },
    // 点击角色弹出模态框
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // excel导出
    async handledDownLoad() {
      // 发请求，获得的数据，解构为rows
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 调用formatJson将数组转换为二维数组
      const data = this.formatJson(rows, header, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工信息列表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 将表头数据和数据进行对应
    formatJson(rows, header, headersRelations) {
      // 让解构得到的rows进行遍历
      // rows是获取到的所有数据
      // item是遍历得到的每一项
      // 并存储到result中
      const result = rows.map(item => {
        // 声明一个空数组
        const arr = []
        // 遍历header
        // 得到的key是 '姓名'  '手机号'  '入职日期'....
        header.forEach(key => {
          // key是遍历后得到的键 姓名，手机号....
          // headersRelations[key] 表示转为username mobile
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = formatDate(value)
          }
          if (englishKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === +value)
            value = obj ? obj.value : '未知'
          }
          // englishKey是对应键的英文 username mobile...
          arr.push(value)
        })
        // arr为每一行的数据
        return arr
      })
      // result为一个完整的二维数组
      return result
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    async getreqGetEmployeeList() {
      this.loading = true
      const { data } = await reqGetEmployeeList(this.page, this.pageSize)
      // console.log(data)
      // 数据
      this.list = data.rows
      // 个数
      this.total = data.total
      // 关闭加载
      this.loading = false
      // console.log(this.list)
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      // 重新渲染
      this.getreqGetEmployeeList()
    },
    // 删除员工功能
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        // 判断如果卡片里的数据只剩下一条并且页数大于1页到的情况下
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 提示用户
        this.$message.success('删除成功')
        // 渲染页面
        this.getreqGetEmployeeList()
      }).catch(() => {
        // console.log('取消')
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
  }
}
</style>
